<script>
import { Component, Emit, Inject, Model, Prop, Provide, Vue, Watch , Ref } from 'vue-property-decorator';
import { State } from 'vuex-class';
import { get_product_page , page_save , upload_file } from "@/api/index.js"
import swiperView from "./components/swiperView/index.vue"
// h5 标签添加弹框
import tagDialog from "./components/dialog/tagDialog.vue"
import { getNodeJson , uuid , deepObjectMerge } from "@/utils/common.js"
// h5 添加标签自定义组件
import hwTag from "./components/hw_tag/index.vue"
// 上传文件
import uploadFile from "./components/uploadFile/index.vue"
import { Loading } from 'element-ui';
import { base_url } from "@/utils/request/config"



@Component
export default class App extends Vue {

    H5_HTML = ""
    cue_light_style = {} // 提示框的样式
    add_component_type = "" // 添加组件的类型
    show_ifrome_html_mask = false // 遮罩层
    component_list = []
    saveLoading = false
    uuid_list = [] // 标签数据 对象 键问自定义生成 保证唯一
    uuid_dom_obj = {} // 自定义dom  的对象节点
    // 添加标签弹框
    tagDialogFormVisible = false
    tag = ""
    // 提示框样式
    lineleft = {}
    linetop = {}
    linebottom = {}
    lineright = {}
    // 加载旧页面需要执行 的脚本
    execute_script = {}
    oldHtmlAttr = {}
    // 添加当前选中dom节点的 按钮 显示
    showAddChild = false
    // 当前操作的dom
    currentDom = ""
    // 当前dom 类型 div img
    currentDomType = "" 

    @State("drop_menu_list") drop_menu_list
    @State("javascript_option") javascript_option

    activated(){
        this.get_product_page()
    }
    get_product_page(){
        get_product_page({ pageName: this.$route.query.pageName }).then(res=>{
            this.oldHtmlAttr.magic_css = []
            this.oldHtmlAttr.magic_id = []
            res.attr.map(item=>{
                if(item.magic_css){
                    if(this.oldHtmlAttr.magic_css.indexOf(item.magic_css) == -1)
                        this.oldHtmlAttr.magic_css.push(item.magic_css)
                }
                if(item.magic_id){
                    if(this.oldHtmlAttr.magic_id.indexOf(item.magic_id) == -1)
                        this.oldHtmlAttr.magic_id.push(item.magic_id)
                }

            })
            // magic_css: "iraggg"
            // magic_id: null
            // h , script 
            this.H5_HTML = res.h
            this.$nextTick(()=>{
                // eval(res.script)
            })
            
            this.currentDom = ""
            this.showAddChild = false
        })
    }
    // 拖放开始
    dragstart(ev){
        this.add_component_type = ev.srcElement.getAttribute('type')
        this.show_ifrome_html_mask = true
	    // ev.dataTransfer.setData("Text",ev.target.id);
    }
    // 拖放中
    ondragover(ev){
        ev.preventDefault();
        if(this.add_component_type == 'swipe'){
            this.cue_light_style = {
                left  : 0,
                height: "200px",
                width : "100%",
                border: "2px solid #ff7b7b"
            }
        }
        // var data=ev.dataTransfer.getData("Text");
        // console.log(data)
        // ev.target.appendChild(document.getElementById(data));
    }
    
    get_uuid(){
        let uid = uuid(6)
        let flag = true
        while (flag){
            if(this.uuid_list.indexOf(uid) == -1){
                this.uuid_list.push(uid)
                flag = false
            }else{
                uid = uuid(6)
                flag = true
            }
        }
        return uid
    }
    // 拖放结束
    drop(ev){
        // ev.preventDefault();
        // 如果是轮播图
        if(this.add_component_type == "swipe"){
            this.component_list.push(this.add_component_type)
            // 删除 添加组件的类型
            this.add_component_type = ""
            // 删除 提示光标样式
            this.cue_light_style = { }
        }else if("DIVTAG" == this.add_component_type){
            // 如果为H5标签 即 自定义dom节点 则存入另外 自定义 dom对象中
            let dom_uuid = this.get_uuid();
            // 组件数据占位
            this.component_list.push(dom_uuid)
            // 添加dom生成所需数据
            this.uuid_dom_obj[dom_uuid] = {
                tag:"div",
                style:{
                    width: "20px",
                    'min-height': '20px',
                    background: "yellow"
                }
            } 
            // this.tagDialogFormVisible = true  IMGTAG
        }else if("IMGTAG" == this.add_component_type){
             // 如果为H5标签 即 自定义dom节点 则存入另外 自定义 dom对象中
            let dom_uuid = this.get_uuid();
            // 组件数据占位
            this.component_list.push(dom_uuid)
            // 添加dom生成所需数据
            this.uuid_dom_obj[dom_uuid] = {
                tag:"img",
                style:{
                    width: "20px",
                    'height': '20px',
                    background: "yellow"
                }
            } 
        }
        console.log(this.add_component_type)
        // 隐藏遮罩层
        this.show_ifrome_html_mask = false
        // var data=ev.dataTransfer.getData("Text");
        // console.log(data)
        // ev.target.appendChild(document.getElementById(data));
    } 
    // 保存dom节点
    save(){
        if(this.saveLoading) return
        this.saveLoading = true
        let component_html = document.getElementById("component_html");
        let newHtml = getNodeJson(component_html.children);
        let xmloption = {} 
        if(window.executeOption){
            // 接口返回的DOM 
            for(let key in executeOption){ 
                if( key == "swiper" ){
                    executeOption[key].map((item , index)=>{
                        if($('#' + item.el).length == 0){
                            // 代表轮播图节点已经没了 则删掉本节点
                            executeOption[key].splice(index,1)
                        }
                    })
                }
            }
        }
        let xml_html = document.getElementById("xml_html");
        for( let item of xml_html.children ){
            if("app" == item.id) xml_html = item
        }

        // console.log(this.oldHtmlAttr)
        // this.oldHtmlAttr.magic_css = []
        // this.oldHtmlAttr.magic_id = []
        let oldHtml = getNodeJson(xml_html.children,(obj)=>{
            if(obj.class){
                let css = ""
                this.oldHtmlAttr.magic_css.map(item=>{ 
                    if(obj.class.indexOf(item) != -1 )
                        css = item
                })
                obj.class = css
            }
            if(obj.id){
                let id = ""
                this.oldHtmlAttr.magic_id.map(item=>{ 
                    if(obj.id.indexOf(item) != -1 )
                        id = item
                })
                obj.id = id
            }
            return obj
        });

        xmloption.oldHtml = oldHtml
        // 组件的DOM 
        xmloption.html = newHtml

        // js 执行脚本 所需要的参数
        xmloption.javascript = deepObjectMerge( this.javascript_option , window.executeOption || {} )
        xmloption.javascript = JSON.parse(JSON.stringify(xmloption.javascript))
        for(let key in xmloption.javascript){
            if( key == "swiper" ){
                xmloption.javascript[key].map((item , index)=>{ delete xmloption.javascript[key][index].fn })
            }
        }
        // console.log(oldHtml)  
        // console.log(newHtml)  
        xmloption.pageName = this.$route.query.pageName
        // console.log(xmloption)
        // return 
        page_save(xmloption).then(res=>{
            this.saveLoading = false
            this.component_list.map(( item , index )=>{
                if(item == "swipe"){
                    // 关闭之前的渲染
                    this.$refs['swiperViewRef' + index].stop()
                }
            })
            // 需要如果有之前 执行的脚本
            if(window.executeOption){
                for(let key in executeOption){
                    if( key == "swiper" ){
                        executeOption[key].map((item , index)=>{
                            item.fn.stop()
                        })
                    }
                }
            }
            
            //  清空页面
            this.H5_HTML = "";
            this.component_list = [];
            // 从接口获取新页面
            this.get_product_page()
        })
    }
    // 添加标签回调
    onChangeDialogFormVisible(value,option){
        console.log( option )
        
    try{

        // return
        this.tagDialogFormVisible=value 
        // name: "img" div
        // text: ""
        if(option.name == "div"){
            let style = { width: "20px", 'min-height': '20px', background: "yellow" }
            let addDom = $(`<div stylejson='${JSON.stringify(style)}' >${option.text}</div>`).css(style)
            $(this.currentDom).append(addDom)
        }else if(option.name == "img"){
            let style = { width: "20px", 'height': '20px', }
            let addDom = $(`<img stylejson='${JSON.stringify(style)}' src="" />`).css(style)
            $(this.currentDom).append(addDom)
        }else{
            $(this.currentDom).text(option.text)
        }
    }catch(e){

    } 
    }
    // 移动事件
    ifrome_html_move(e){
        let el = $(e.srcElement); 
        this.lineleft = {
            height:el.innerHeight() + 2 + "px",
            top: el.offset().top + "px" ,
            left : el.offset().left  + "px" 
        }
        this.linetop = {
            width:el.innerWidth() + 2 + "px",
            top: el.offset().top - 3 + "px" ,
            left : el.offset().left + "px" 
        }
        this.linebottom = {
            width:el.innerWidth()  + 2  + "px",
            top: el.offset().top + el.innerHeight() + 1 + "px",
            left : el.offset().left + "px"
        }
        this.lineright = {
            height:el.innerHeight()  + 2  + "px",
            top: el.offset().top + "px",
            left : el.offset().left+ el.innerWidth()+ "px"
        }
        
    }
    ifrome_html_mouseover(e){ 
        // console.log("移入")
    }
    ifrome_html_mouseout(e){ 
        try{
            if(e.toElement.className == "content"){ 
                this.lineleft = { }
                this.linetop = { }
                this.linebottom = { }
                this.lineright = { }
            }
        }catch(e){
            // console.log(e)
        }
    }
    ifrome_html_click(e){
        this.currentDom = e.srcElement
        // console.log(this.currentDom.localName)
        this.currentDomType = this.currentDom.localName
        // currentDomType
        this.showStyleJson()
    }
    showStyleJson(){
        let style = $(this.currentDom).attr("stylejson")
        if(style){
            this.showAddChild = true
            this.$nextTick(()=>{
                $('#style_json').jsonEditor( JSON.parse(style) , { 
                    change: (data)=>{ 
                        console.log(data)
                        $(this.currentDom).attr("stylejson",JSON.stringify(data))
                        $(this.currentDom).css(data)
                        // setTimeout(()=>{ this.save() },200) 
                    },
                    propertyclick: (path) => {
                        // console.log(path)
                    }
                });
            })
        }
    }
    delete_current_node(){
        $(this.currentDom).remove()
        this.$nextTick(()=>{ this.save() }) 
    }
    get_parent_node(){
        this.currentDom = $(this.currentDom).parent() 
        this.currentDomType = this.currentDom[0].localName
        this.showStyleJson()
    } 
    next_node(){
        if($(this.currentDom).nextAll().length > 0){
            $(this.currentDom).next().after($(this.currentDom).prop('outerHTML'));
            $(this.currentDom).remove();
            this.$nextTick(()=>{ this.save() }) 
        }
    }
    prev_node(){
        
        if($(this.currentDom).prevAll().length > 0){
            $(this.currentDom).prev().before($(this.currentDom).prop('outerHTML'));
            $(this.currentDom).remove();
            this.$nextTick(()=>{ this.save() }) 
        } 
    }
    copy_node(){
        $(this.currentDom).after($(this.currentDom).clone(true));
    }
    page_factory_move(){
        this.show_ifrome_html_mask=false ;
        this.cue_light_style = {}
    }
    // 上传文件执行方法
    onUploadFile(option){
        let loadingInstance = Loading.service({ fullscreen: true })
        var formData = new FormData();
        formData.append('flie', option.file);
        upload_file(formData).then(res=>{
            // console.log(res)
            // http://106.12.76.26:3560/static/uploads/2020/06/16/1592301207346982.png
            
            $(this.currentDom).attr("src", res.replace("/public", base_url + "/static") )
            loadingInstance.close();
        })
    }
    render(createElement){
        // this.currentDomType div img
        return (
            <div class="page_factory" onMousemove={ this.page_factory_move }   >
                <div class="nav" >
                    {this.drop_menu_list.map(item=>(<div draggable="true" type={item.type} ondragstart={this.dragstart} > <img src={require("@/assets/image/icon_menu.png").default} /> <div class="name" >{item.title}</div> </div>))}
                </div>
                <div class="content"  >
                    <div class="ifrome_html" 
                        onMouseover={this.ifrome_html_mouseover} 
                        onMouseout={this.ifrome_html_mouseout} 
                        onMousemove={this.ifrome_html_move}  
                        onClick={this.ifrome_html_click}
                    >
                        <div id="xml_html" domPropsInnerHTML={this.H5_HTML}></div>
                        <div id="component_html" >
                            {
                                this.component_list.map(( item , index )=>{
                                    if(this.uuid_dom_obj[item]){
                                        return <hwTag option={this.uuid_dom_obj[item]} />
                                    }else if(item == "swipe") return <swiperView ref={'swiperViewRef' + index} />
                                })
                            }
                        </div>
                        <div class="cue_light" style={this.cue_light_style} ></div>
                    </div>
                    { /* 拖放事件 显示的 遮罩层 */ }
                    <div
                        ondrop={this.drop} 
                        ondragover={this.ondragover} 
                        class="mask" 
                        style={{ display: this.show_ifrome_html_mask ? 'block' : 'none' }}
                    ></div>
                </div>
                <div class="navr" >
                    <div>
                        <div id="style_json" class="json-editor" ></div>
                        {this.showAddChild&&(<el-button onClick={ this.get_parent_node } style="margin-top: 20px;" >父节点</el-button>)}
                        { (this.showAddChild && this.currentDomType == 'div') && (<el-button onClick={()=>{ this.tagDialogFormVisible = true }} style="margin-top: 20px;margin-left:0;" >添加子节点</el-button>) }
                        { (this.showAddChild && this.currentDomType == 'img') && (<uploadFile onUploadFile={this.onUploadFile} />) }
                        {this.showAddChild&&(<el-button onClick={this.delete_current_node} style="margin-top: 20px;" >删除节点</el-button>)}
                        {this.showAddChild&&(<el-button onClick={this.prev_node} style="margin-top: 20px;" >上移</el-button>)}
                        {this.showAddChild&&(<el-button onClick={this.next_node} style="margin-top: 20px;" >下移</el-button>)}
                        {this.showAddChild&&(<el-button onClick={this.copy_node} style="margin-top: 20px;" >复制节点并插入</el-button>)}
                        
                        
                    </div>
                    <div  class="bt" ><el-button onClick={this.save} >保存</el-button></div> 
                </div>
                <div class="lineleft" style={this.lineleft} ></div>
                <div class="linetop"  style={this.linetop} ></div>
                <div class="linebottom"  style={this.linebottom} ></div>
                <div class="lineright"  style={this.lineright} ></div>
                <tagDialog 
                    tagDialogFormVisible={this.tagDialogFormVisible} 
                    onChangeDialogFormVisible={this.onChangeDialogFormVisible} 
                />
            </div>
        )
    }
}
</script>

<style lang="less" >
@import "./index.less";
</style>